package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 * NOTA: il tipo boolean viene mappato da JDBC sempre
 * con un tipo BIT
 * @author Gianfranco Murador
 */
public class XmlBit extends XmlTypes {

    public XmlBit() {
    }

    public XmlBit(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData metaData) {
        Element xtype;
        Element restriction, maxlength;
        fragment = doc.createDocumentFragment();

        if (metaData.getDisplaySize() != null) {
            // è un BIT
            typeName += "_" + metaData.getDisplaySize();
        } else {
            // è un BOOL
            typeName = "BOOL";
        }
        metaData.setXschemaTypeName(typeName);

        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName);
        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");


        if (metaData.getDisplaySize() != null) {
            // se è un bit
            Integer length = metaData.getDisplaySize();
            restriction.setAttribute("base", "xs:string");
            Element enum1 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:enumeration");
            enum1.setAttribute("value", "1");
            Element enum0 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:enumeration");
            enum0.setAttribute("value", "0");
            restriction.appendChild(enum0);
            restriction.appendChild(enum1);
            maxlength = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:maxLength");
            maxlength.setAttribute("value", length.toString());
            restriction.appendChild(maxlength);
        } else {
            // se è un boolean
            restriction.setAttribute("base", "xs:boolean");
        }
        //
        xtype.appendChild(restriction);
        fragment.appendChild(xtype);

    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {


        typeName = cmd.getTypeName();

        if (typeName.equals("BIT")) {
            buildFragment(cmd);
            return fragment;
        } else {
            // Fa una richiesta di responsabilità
            // al prossimo oggetto della catena
            return nextType.getSchemaType(cmd);
        }


    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {

        if (baseType.startsWith("BIT")) {
            Byte b = new Byte(value);
            return b;
        } else {

            if (baseType.startsWith("BOOL")) {

                Boolean b = new Boolean(value);
                return b;

            } else {

                return nextType.getXSchemaToJavaType(baseType, value);
            }
        }
    }
}

